import global from '@/common/global.js';
import store from '@/store';
import Request from '@/common/luch-request/index.js'
import $api from "./api.js"
const http = new Request({
	baseURL: global.baseUrl
});
let isShowModal = true;

http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	config.header['X-Requested-With'] = 'XMLHttpRequest';
	config.header['token'] = uni.getStorageSync("eduToken");
	config.data = Object.assign({}, config.data, {})
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})
http.interceptors.response.use((response, ) => {
	/* 对响应成功做点什么 可使用async await 做异步操作*/
	store.dispatch("loading/loading", true)
	if (response.data && (response.data.Result == 1 || response.data.Result == 0)) {
		return response.data;
	} else if (response.data && response.data.code == 0) {
		return response.data;
	} else {
		console.log("response.data.code=======>", response.data.code)
		if (response.data.code == 401) {
			store.dispatch('eduUser/logOut')
			store.dispatch("user/autologin")
			return {
				data: []
			};
		} else {
			uni.showToast({
				title: response.data.msg,
				duration: 1500,
				icon: "none"
			});
		}
	}

}, (response) => {
	/*  对响应错误做点什么 （statusCode !== 200）*/
	uni.showToast({
		title: '服务器繁忙，请稍后再试',
		icon: 'none',
		duration: 2000
	});
	return Promise.reject(response)
});

export async function getUserInfo(data) {
	let code = uni.getStorageSync("eduCode")
	console.log("getUserInfo=====>", $api.edu.getUserInfoApi)
	try {
		let res = await http.get($api.edu.getUserInfoApi, {
			params: {
				usercode: code
			}
		});
		if (res.Data && res.Data.id) {
			console.log(res.Data)
			return res.Data;
		} else {
			return {}
		}
	} catch (e) {
		return {}
	}
}


export async function getOpenId(code) {
	let eduOpenid = uni.getStorageSync("eduOpenid")
	console.log("getOpenId=====>", $api.edu.getOpenId,code)
	try{
		let res = await http.get($api.edu.getOpenId,{params:{code:code}});
		console.log(res)
		if(res.openId){
			console.log(res.openId)
			return res.openId;
		}else{
			return ""
		}
	}catch(e){
		return ""
	}
}


// 封装uni.login为返回Promise的形式
export function getOpenIdCode() {
  return new Promise((resolve, reject) => {
    uni.login({
      success(res) {
        if (res.code) {
          resolve(res.code); // 成功时解析code
        } else {
          resolve(""); // 失败时拒绝并给出错误信息
        }
      },
      fail: err => {
        resolve(""); // 登录失败时拒绝并给出错误信息
      }
    });
  });
}